package com.xiaoming.service;

import com.alibaba.fastjson.JSONObject;
import com.xiaoming.adapter.MessageAdapter;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

/**
 * @author xiaoming
 * @Date 2020/3/11
 */
@Service
public class EmailService implements MessageAdapter {

    @Value("${email.subject}")
    private String subject;

    @Value("${email.text}")
    private String text;

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;



    @Override
    public void sendMsg(JSONObject body) {
        String email = body.getString("email");
        if (StringUtils.isEmpty(email)) {
            return;
        }
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        // 发送
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(email);
        // 标题
        simpleMailMessage.setSubject(subject);
        // 内容
        simpleMailMessage.setText(text.replace("{}", email));
        mailSender.send(simpleMailMessage);

    }
}
